package cn.diancan.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Config { 
	public static List<ImageSize> imageSizes=new ArrayList<ImageSize>(); 
	public static Dir dir=null; 
	//存在数据库的Code
	public static Map<String,Dir> dirs=new HashMap<String,Dir>(); 
	
	/**
	 * @param basepath
	 */
	@SuppressWarnings("unchecked")
	public static void initConfig(){
		Document document =null; 
		try {
			SAXReader reader = new SAXReader();     
			File f = new File(new Config().getClass().getClassLoader().getResource("config.xml").getPath());
			InputStream in = new FileInputStream(f);
			document = reader.read(in);
			//Node node_host= document.selectSingleNode("/ymconfig/accesshost");
			//ROOTPATH=node_host.getText(); 
			List<Element> dataListDir = document.selectNodes("/ymconfig/dirs/dir");
			for (Iterator<Element> i_data = dataListDir.iterator(); i_data.hasNext();) {
				Element dataEle = i_data.next();
				Dir dir = new Dir();
				dir.setDircode(dataEle.element("dircode").getTextTrim());
				dir.setRootpath(dataEle.element("rootpath").getTextTrim());
				dir.setAccesshost(dataEle.element("accesshost").getTextTrim());
				dir.setIsuse(Boolean.valueOf(dataEle.element("isuse").getTextTrim()));
				dir.setDownhost(dataEle.element("downhost").getTextTrim());
				if(dir.getIsuse()){
					Config.dir= dir;
				} 
				dirs.put(dir.getDircode(),dir);
			} 
			List<Element> dataListImagesize = document.selectNodes("/ymconfig/imagesizes/imagesize");
			for (Iterator<Element> i_data = dataListImagesize.iterator(); i_data.hasNext();) {
				Element dataEle = i_data.next();
				ImageSize imageSize = new ImageSize();
				imageSize.setHeight(Integer.valueOf(dataEle.element("height").getTextTrim()));
				imageSize.setWidth(Integer.valueOf(dataEle.element("width").getTextTrim()));
				imageSizes.add(imageSize);
			}
			System.out.println("配置读取文件成功");
			return ;
		} catch (DocumentException e) { 
			e.printStackTrace(); 
		} catch (Exception e) { 
			e.printStackTrace();
		}
		System.out.println("配置读取文件失败");
		return ;
		
		/*Properties prop = new Properties();
		InputStream in = null ;
		try {
				in = new FileInputStream(basepath+"WEB-INF/classes/config.properties");
	            prop.load(in);   
	            Config.ROOTPATH = prop.getProperty("rootpath").trim();   
	            Config.ACCESSHOST = prop.getProperty("accesshost").trim();
	            Config.DIRCODE = prop.getProperty("dircode").trim();
	    } catch (IOException e) {   
	            e.printStackTrace();   
	    }finally{
	    	try { 
				in.close();
			} catch (IOException e) { 
				e.printStackTrace();
			}
	    }*/
	}
	
	
}
